﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args.WizardForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn.ControlModel;
using Kingdee.BOS.Core.DynamicForm.PlugIn.WizardForm;
using Kingdee.BOS.Core.List;
using Kingdee.BOS.Core.Report;
using Kingdee.BOS.Model.ReportFilter;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using System;
using System.ComponentModel;
using System.Data.SqlClient;
using System.Data;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.SqlBuilder;

namespace LM.CB.K3Cloud.Plugin
{
    /// <summary>
    /// 预算成本导航表单插件
    /// </summary>
    /// <remarks>
    /// 功能：1.校验组织，年，月必填 
    ///      2.检查当月原药市场价必填
    ///      3.
    /// 创建人：lxl
    /// 创建日期：2024-05-18
    /// </remarks>
    [Description("考核成本导航表单插件")]
    [Kingdee.BOS.Util.HotUpdate]
    public class KHCostBillPlugin : AbstractWizardFormPlugIn
    {
        string OrgId = "";
        string year = "";
        string Month = "";
        private ProgressBar _progressBar = null;//进度条
        //private int _progressValue = 0;//当前进度
        private const string ProcessRateValue = "ProcessRateValue";
        bool islock = false;

        public override void OnInitialize(InitializeEventArgs e)
        {
            this._progressBar = this.View.GetControl<ProgressBar>("F_RDLV_ProgressBar");//进度条

        }

        /// <summary>
        /// 操作步骤切换前事件
        /// </summary>
        /// <param name="e"></param>
        public override void WizardStepChanging(WizardStepChangingEventArgs e)
        {
            if (e.UpDownEnum == 1)
            {
                // 校验第一步组织，年度，月份信息内容是否填写
                if (e.OldWizardStep.Key.Equals("FWizard0", StringComparison.OrdinalIgnoreCase))
                {
                    DynamicObject Org = this.View.Model.DataObject["F_RDLV_OrgId"] as DynamicObject;
                    if (Org != null)
                    {
                        OrgId = Org["ID"].ToString(); // 组织编码
                    }
                    year = Convert.ToString(this.Model.GetValue("F_RDLV_year"));
                    Month = Convert.ToString(this.Model.GetValue("F_RDLV_Month"));
                    if (string.IsNullOrWhiteSpace(OrgId) || string.IsNullOrWhiteSpace(year) || string.IsNullOrWhiteSpace(Month))
                    {
                        this.View.ShowWarnningMessage("先维护组织，年度，月份信息!");
                        e.Cancel = true;
                        return;
                    }
                }
                // 合法性校验只要有不通过时点击下一步触发提示
                if (e.OldWizardStep.Key.Equals("FWizard1", StringComparison.OrdinalIgnoreCase) && islock)
                {
                    this.View.ShowWarnningMessage("合法新检测有结果有不通过数据请先处理");
                    e.Cancel = true;
                    return;
                }
            }
        }

        /// <summary>
        /// 操作步骤切换后事件
        /// </summary>
        /// <param name="e"></param>
        /// <summary>
        /// 操作步骤切换后事件
        /// </summary>
        /// <param name="e"></param>
        public override void WizardStepChanged(WizardStepChangedEventArgs e)
        {
            base.WizardStepChanged(e);
            if (e.UpDownEnum == 1)
            {
                if (e.WizardStep.ContainerKey == "F_RDLV_STEP2")
                {    //检查当月是否有原药市场价格      
                    string sql = $@"/*dialect*/SELECT t2.F_QLTK_priceNoTax,t1.fid FROM
		 QLTK_t_YYZYtPrice t1 join  QLTK_t_YYZYtPriceE t2--内部转移价表体
		 on t1.fid=t1.fid  and t1.F_QLTK_YEAR={year} and t1.F_QLTK_MONTH={Month} and t1.FUSEORGID={OrgId}";
                    DynamicObjectCollection dy = DBUtils.ExecuteDynamicObject(Context, sql.ToString());
                    if (dy.Count > 0)
                    {
                        this.View.Model.DeleteEntryData("F_RDLV_CheckEntity");
                        this.Model.CreateNewEntryRow("F_RDLV_CheckEntity");//合法性检测单据体赋值
                        this.Model.SetValue("F_RDLV_CheckItem", "原药内部转移价"); //检查项
                        this.Model.SetValue("F_RDLV_CheckResult", "0"); //检查结果
                        this.Model.SetValue("F_RDLV_ShowRuslt", "当月已维护原药转移价"); //明细
                        this.View.UpdateView("F_RDLV_CheckEntity");
                        islock = false;
                    }
                    else
                    {
                        this.View.Model.DeleteEntryData("F_RDLV_CheckEntity");
                        this.Model.CreateNewEntryRow("F_RDLV_CheckEntity");//合法性检测单据体赋值
                        this.Model.SetValue("F_RDLV_CheckItem", "原药内部转移价"); //检查项
                        this.Model.SetValue("F_RDLV_CheckResult", "1"); //检查结果
                        this.Model.SetValue("F_RDLV_ShowRuslt", "当月未维护原药转移价"); //明细
                        this.View.UpdateView("F_RDLV_CheckEntity");
                        islock = true;
                    }
                }

                if (e.WizardStep.ContainerKey == "F_RDLV_STEP3")
                {
                    this.View.GetControl("F_RDLV_YSCBCX").Visible = false;//隐藏链接
                    // 启动进度条，每个2s，到服务器获取一次进度。
                    // 如果进度达到了100，则自动停止
                    this._progressBar.Start(2);
                    // 开启一个新线程，处理需要长时间进行的业务
                    Kingdee.BOS.KDThread.MainWorker.QuequeTask(this.Context,
                        () =>
                        {
                            try
                            {
                                // TODO: 异步处理
                                int result = GetCB_CostCalBill(year, Month, OrgId);//获取成本计算单数据
                                //将计算出来的数据存储到数据表(每月替换生产的制剂成本)
                                string sql =
                                    $@"EXEC [dbo].[dev_p_KhCostTable] @fyear={year},
                                    @fmonth={Month},@forgid={OrgId}";
                                DBUtils.Execute(Context, sql);
                                //将当月生产的和台账的数据加权

                            }
                            catch (Exception ex)
                            {
                                this.View.ShowErrMessage(ex.Message);
                            }
                            finally
                            {
                                this.View.Session["ProcessRateValue"] = 100;
                                this.View.SendDynamicFormAction(this.View);
                            }
                        },
                        new Action<Kingdee.BOS.KDThread.AsynResult>((ar) =>
                        {
                            if (ar.Success == false && ar.Exception != null)
                            {
                                return;
                            }
                        }));
                }
            }
        }
        /// <summary>
        /// 获取成本计算单数据
        /// </summary>
        /// <param name="year"></param>
        /// <param name="month"></param>
        /// <param name="orgId"></param>
        /// <exception cref="NotImplementedException"></exception>
        private int GetCB_CostCalBill(string fyear, string fmonth, string forgId)
        {
            // 加载过滤条件元数据
            var reportFilterMetadata = FormMetaDataCache.GetCachedFormMetaData(Context, "CB_CostCalFilter");
            var reportFilterServiceProvider = reportFilterMetadata.BusinessInfo.GetForm().GetFormServiceProvider();
            // 创建报表过滤模型
            var model = new SysReportFilterModel();
            model.SetContext(Context, reportFilterMetadata.BusinessInfo, reportFilterServiceProvider);
            model.FormId = reportFilterMetadata.BusinessInfo.GetForm().Id;
            // 加载字段比较元数据
            var filterMetadata = FormMetaDataCache.GetCachedFilterMetaData(Context);
            model.FilterObject.FilterMetaData = filterMetadata;

            // 加载报表元数据。
            var reportMetadata = FormMetaDataCache.GetCachedFormMetaData(Context, "CB_CostCalBill");
            model.InitFieldList(reportMetadata, reportFilterMetadata);
            model.GetSchemeList();
            // 获取过滤方案，可以通过LoadScheme("Id")，查询报表默认存在的一些过滤方案
            //SELECT * FROM T_BAS_FILTERSCHEME where fschemename='考核成本金蝶报表取数_勿删'
            string fschemeid = "66499febc60c29"; // 过滤方案的ID
            DynamicObject orgObj = LoadBDObject("ORG_Organizations", forgId);//构建数据包
            model.Load(fschemeid);
            var filter = model.GetFilterParameter();
            // 设置日期
            filter.CustomFilter["ACCTGORGID"] = orgObj;
            filter.CustomFilter["ACCTGORGID_id"] = forgId;
            filter.CustomFilter["Year"] = fyear;
            filter.CustomFilter["Period"] = fmonth;
            filter.CustomFilter["FEndYear"] = fyear;
            filter.CustomFilter["FEndPeriod"] = fmonth;
            // 报表参数
            IRptParams p = new RptParams();
            p.FormId = reportFilterMetadata.BusinessInfo.GetForm().Id;
            p.StartRow = 1;
            // StartRow和EndRow是报表数据分页的起始行数和截至行数，
            // 一般取所有数据，所以EndRow取int最大值。
            p.EndRow = int.MaxValue;
            p.FilterParameter = filter;
            p.FilterFieldInfo = model.FilterFieldInfo;

            IPermissionService permissionService = ServiceFactory.GetPermissionService(Context);
            p.BaseDataTempTable.AddRange(permissionService.GetBaseDataTempTable(Context, reportMetadata.BusinessInfo.GetForm().Id));
            var param = new MoveReportServiceParameter(Context, reportMetadata.BusinessInfo, Guid.NewGuid().ToString(), p);
            #region 新建结果表
            DataTable dtResult = new DataTable();
            dtResult.Columns.Add("fyear", typeof(int));// 年
            dtResult.Columns.Add("fmonth", typeof(int));// 月
            dtResult.Columns.Add("FPRODUCTID", typeof(string));// 产品ID
            dtResult.Columns.Add("FMATERIALFIELD_FNUMBER", typeof(string));// 物料编码
            dtResult.Columns.Add("FBASICUNITFIELD_FNAME", typeof(string));// 基本单位名称
            dtResult.Columns.Add("FProductUseQty", typeof(decimal));// 物料单耗
            dtResult.Columns.Add("FProductUseCost", typeof(decimal));// 物料实际用量
            dtResult.Columns.Add("FCompleteAmount", typeof(decimal));// 物料完工金额
            dtResult.Columns.Add("fcostitemid_fnumber", typeof(string));// 成本项目编码
            dtResult.Columns.Add("FCOSTITEMID_FNAME", typeof(string));// 成本项目\
            dtResult.Columns.Add("FCompleteQty", typeof(decimal));// 完工数量\
            dtResult.Columns.Add("forgid", typeof(int));// 组织\
            dtResult.Columns.Add("FPRODUCTID_FNUMBER", typeof(string));//产品编码
            dtResult.Columns.Add("FPRODUCTID_FNAME", typeof(string));//产品名称
            dtResult.Columns.Add("fidentityid", typeof(int));//序号
            dtResult.Columns.Add("FMATERIALFIELD_FNAME", typeof(string));//序号
            #endregion

            // 简单账表使用GetReportData方法 
            ISysReportService sysReporSservice = ServiceFactory.GetSysReportService(Context);
            using (DataTable dt = sysReporSservice.GetCrossReportData(param).DataSource)
            {
                foreach (DataRow item in dt.Rows)
                {
                    DataRow drw = dtResult.NewRow();
                    drw["fyear"] =fyear;drw["fmonth"] = fmonth;
                    drw["FPRODUCTID"] = item["FPRODUCTID"];
                    drw["FMATERIALFIELD_FNUMBER"] = item["FMATERIALFIELD_FNUMBER"];
                    drw["FBASICUNITFIELD_FNAME"] = item["FBASICUNITFIELD_FNAME"];
                    drw["FProductUseQty"] = item["FProductUseQty"];
                    drw["FProductUseCost"] = item["FProductUseCost"];
                    drw["FCompleteAmount"] = item["FCompleteAmount"];
                    drw["fcostitemid_fnumber"] = item["fcostitemid_fnumber"];
                    drw["FCOSTITEMID_FNAME"] = item["FCOSTITEMID_FNAME"];
                    drw["FCompleteQty"] = item["FCompleteQty"];
                    drw["forgid"] = forgId;
                    drw["FPRODUCTID_FNUMBER"] = item["FPRODUCTID_FNUMBER"];
                    drw["FPRODUCTID_FNAME"] = item["FPRODUCTID_FNAME"];
                    drw["fidentityid"] = item["fidentityid"];
                    drw["FMATERIALFIELD_FNAME"] = item["FMATERIALFIELD_FNAME"];
                    dtResult.Rows.Add(drw);
                }
                ServiceFactory.CloseService(sysReporSservice);
                ServiceFactory.CloseService(permissionService);
            }
            DBUtils.Execute(this.Context, $"DELETE FROM  dev_t_KHCostData WHERE fyear={fyear} AND fmonth={fmonth} and forgid={forgId}");
            //将数据存到数据表实体表中
            string connectionString = "Data Source=10.10.11.101;database=AIS20240514124535;Uid=sa;Pwd=123qwe!@#;";
            SqlBulkCopy sqlbulkcopy = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.UseInternalTransaction);
            sqlbulkcopy.DestinationTableName = "dev_t_KHCostData";//数据库中的自己创建表名:临时表名
            sqlbulkcopy.WriteToServer(dtResult);
            return 1;
        }



        /// <summary>
        /// 进度条，咨询进度
        /// </summary>
        /// <param name="e"></param>
        public override void OnQueryProgressValue(QueryProgressValueEventArgs e)
        {

            base.OnQueryProgressValue(e);
            if (!this.View.Session.ContainsKey(ProcessRateValue))
            {
                this.View.Session.Add(ProcessRateValue, 0);
            }
            // 更新进度条
            e.Value = (int)this.View.Session[ProcessRateValue];
            if (e.Value >= 100)
            {
                this.View.GetControl("F_RDLV_YSCBCX").Visible = true;//显示链接
            }

        }

        public override void ButtonClick(ButtonClickEventArgs e)
        {
            base.ButtonClick(e);
            switch (e.Key.ToUpper())
            {
                case "F_RDLV_YSCBCX":   //点击"考核成本查询"链接

                    //BillShowParameter g_aBParameter = new BillShowParameter();
                    //g_aBParameter.FormId = "RDLV_BugCostTree";    //预算成本树形查询
                    //g_aBParameter.ParentPageId = this.View.PageId;
                    //g_aBParameter.CustomParams.Add("F_RDLV_ORGID", OrgId);
                    //g_aBParameter.CustomParams.Add("F_RDLV_Year", year);
                    //g_aBParameter.CustomParams.Add("F_RDLV_Month", Month);
                    //this.View.ShowForm(g_aBParameter);
                    ListShowParameter showParam = new ListShowParameter();
                    showParam.Context = this.Context;
                    showParam.OpenStyle.ShowType = ShowType.MainNewTabPage;
                    showParam.PageId = Guid.NewGuid().ToString();
                    showParam.FormId = "QLTK_KHCOSTRpt";  //考核成本
                    showParam.IsLookUp = true;
                    //showParam.ListFilterParameter.Filter = "F_RDLV_ORGID='" + OrgId + "' and F_RDLV_Year='" + year + "' and F_RDLV_Month='" + Month + "'";
                    //showParam.OpenStyle.ShowType = ShowType.Modal;
                    this.View.ShowForm(showParam);
                    break;
            }
        }


        /// 构造基础资料
        /// </summary>
        /// <param name="myFilter"></param>
        private DynamicObject LoadBDObject(string formId, string id)
        {
            FormMetadata meta = MetaDataServiceHelper.Load(this.Context, formId) as FormMetadata;
            // 构建查询参数，设置过滤条件    
            QueryBuilderParemeter queryParam = new QueryBuilderParemeter();
            queryParam.FormId = formId;
            queryParam.BusinessInfo = meta.BusinessInfo;
            queryParam.FilterClauseWihtKey = string.Format(" forgid = '{0}'", id);
            var bdObjs = BusinessDataServiceHelper.Load(this.Context, meta.BusinessInfo.GetDynamicObjectType(), queryParam);
            return bdObjs[0];
        }
    }
}
